<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div class="product-import no-margin small-padding">
      <div class="import-container">
        <div class="product-flex">
          <Title title="订单上传" />
          <el-button :loading="submitLoading" :disabled="submitDisabled" size="small" type="primary" class="submit-btn" @click="submit">提交</el-button>
        </div>
        <div class="title-tip">请到有赞后台下载对应的文件并上传，每份文件只允许上传一份，多次上传以最新的上传为准。全部文件上传完成后请提交，如果当前有执行中的任务那么将无法提交新的文件。</div>
        <div class="main">
          <div v-for="(item) in importList" :key="item.key" class="list">
            <upAttachment
              v-loading="item.loading || item.checkLoading"
              :hide-confirm="true"
              :file-list="params[item.key]"
              :validate-upload="validateUpload(item)"
              :element-loading-text="item.checkLoading?'检查文件中...':'上传中...'"
              btn-text="上传文件"
              hide-clip-up
              accept=".csv,.xls,.xlsx"
              @upProgress="upProgress(item)"
              @complateSetData="complateSetData($event, item)"
              @upLoadError="upLoadError(item)">
              <div v-if="params[item.key] && params[item.key].length" class="import-container-file-list">
                <div
                  v-for="(fileItem, index) in params[item.key]"
                  :key="index"
                  :class="{'is-error': fileItem.isError}"
                  class="file-item">
                  <img :src="fileItem.isError?errorIcon:successIcon" class="icon-img" alt="">
                  <div class="file-item-content">
                    <ToolTip :content="fileItem.name" :extend-icon="fileItem.isError?docErrIcon:docIcon" class="name" />
                    <i class="delete-icon el-icon-close" @click.stop="removeFileList(item)" />
                  </div>
                </div>
              </div>
              <div v-else class="upload-main">
                <img :src="UploadIcon" alt="">
                <div class="text"><span class="tip">请上传</span><span class="name">《{{ item.name }}》</span></div>
              </div>
              <div slot="fileList"/>
            </upAttachment>
            <div class="upload-tip" @click="goHelp(item)">如何获取{{ item.name }}？</div>
          </div>
        </div>
      </div>
      <LogList ref="logRef" />
    </div>
  </div>
</template>

<script>
import Title from '@/components/Title';
import upAttachment from '@/components/Common/upAttachment/index';
import { checkReport, submitReport } from '@/api/commerce';
import LogList from './model/logList';
import ElMessage from '@/utils/message';
import UploadIcon from '@/assets/orderlist/upload.png';
import successIcon from '@/assets/auditProcess/status4.png';
import errorIcon from '@/assets/config/upload_error.png';
import docIcon from '@/assets/config/doc.png';
import docErrIcon from '@/assets/config/doc_error.png';
import { mapState } from 'vuex';

export default {
  name: 'ProductImport',
  components: { Title, upAttachment, LogList },
  data() {
    return {
      UploadIcon, successIcon, errorIcon, docIcon, docErrIcon,
      // 1：订单报表 2：商品报表 3：商品维度报表 4：分销商品表 5：商品表
      importList: [
        // v3.4.6隐藏订单报表
        // { name: '订单报表', type: 1, loading: false, checkLoading: false, key: 'orderReport' },
        { name: '商品报表', type: 2, loading: false, checkLoading: false, key: 'goodsReport' },
        { name: '商品维度报表', type: 3, loading: false, checkLoading: false, key: 'goodsDimensionReport' },
        { name: '分销-订单维度', type: 4, loading: false, checkLoading: false, key: 'distributionReport' },
        { name: '商品表', type: 5, loading: false, checkLoading: false, key: 'googsTable' }
      ],
      submitLoading: false,
      params: {
        // orderReport: [],
        goodsReport: [],
        goodsDimensionReport: [],
        distributionReport: [],
        googsTable: []
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    submitDisabled() {
      return Object.keys(this.params).some(i => {
        return this.params[i].length === 0 || this.params[i][0].isError;
      });
    }
  },
  methods: {
    submit() {
      const params = {};
      Object.keys(this.params).forEach(i => {
        params[i] = this.params[i][0].url;
      });
      this.submitLoading = true;
      submitReport(params).then(res => {
        this.submitLoading = false;
        if (res.code === 200) {
          ElMessage.success('提交成功');
          this.$refs.logRef.getLogList(true);
          this.params = {
            // orderReport: [],
            goodsReport: [],
            goodsDimensionReport: [],
            distributionReport: [],
            googsTable: []
          };
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    validateUpload(item) {
      return (file) => {
        if (item.checkLoading) return;
        return new Promise((resolve, reject) => {
          const formData = new FormData();
          formData.append('fileData', file);
          formData.append('type', item.type);
          formData.append('fileName', file.name);
          const errorfileData = {
            name: file.name, url: file, time: new Date().getTime(), isError: true
          };
          item.checkLoading = true;
          checkReport(formData).then(res => {
            item.checkLoading = false;
            if (res.code === 200) {
              resolve(true);
            } else {
              this.$set(this.params, item.key, [errorfileData]);
              reject(false);
            }
          }).catch((err) => {
            if (err.message && err.message.indexOf('timeout') !== -1) {
              this.$message.error('上传文件超时，请重新上传');
            }
            item.checkLoading = false;
            this.$set(this.params, item.key, [errorfileData]);
            reject(false);
          });
        });
      };
    },
    upProgress(item) {
      item.loading = true;
    },
    complateSetData({ data, fileName }, item) {
      item.loading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      this.$set(this.params, item.key, [fileList]);
    },
    removeFileList(item) {
      this.$set(this.params, item.key, []);
    },
    upLoadError(item) {
      this.$message.error(`${item.name}上次失败`);
    },
    goHelp(item) {
      let routeUrl = null;
      routeUrl = this.$router.resolve({
        name: 'help',
        query: {
          keyWord: `获取${item.name}`,
          model: 'commerceOrder',
          isSearch: true // 从弹窗搜索进行跳转进入则不走列表页面create中调用接口的逻辑
        }
      });
      if (routeUrl) window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
$itemHeight: 130px;
.product-import {
  background-color: #fff;
  padding: 11px 16px 16px 16px;
  margin:	16px;
  min-height: calc(100vh - 64px);
}
.import-container {
  .title-tip {
    font-size: 12px;
    color: #838791;
    padding: 8px;
    background: #fafbff;
    border: 1px solid #e6edff;
    border-radius: 4px;
    margin: 7px 0 8px 0;
  }
  .main {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-bottom: 20px;
    .list {
      flex: 1;
      margin-right: 8px;
      &:last-child {
        margin-right: 0;
      }
      ::v-deep .el-loading-text {
        margin: 45px 0 0;
      }
    }
  }
  &::v-deep {
    .fb-upload-container , .el-upload .el-upload-dragger {
      height: $itemHeight !important;
      width: 100% !important;
    }
    .el-upload-dragger  {
      background-color: #fafafa;
      border: 1px dashed #ddd !important;
      color: #666;
      position: relative;
      .loading-text {
        display: flex;
        align-items: center;
        position: absolute;
        justify-content: center;
        width: 100%;
        height: 100%;
        background-color: rgba($color: #fff, $alpha: 0.8);
      }
      &.is-dragover {
        border-color: #406eff !important;
      }
      &:hover {
        border-color: #406eff !important;
      }
    }
  }
}
.upload-main {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  img {
    width: 40px;
    height: 40px;
    margin-bottom: 4px;
  }
  .text {
    font-size: 14px;
    .tip {
      color: #406EFF;
    }
    .name {
      color: #333333;
    }
  }
}
.import-container-file-list {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 10px;

  .delete-icon {
    font-size: 14px;
    color: #999;
    cursor: pointer;
    display: none;
  }
  .file-item {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    width: 100%;
    .icon-img {
      width: 24px;
      height: 24px;
      margin-bottom: 12px;
    }
    .file-item-content {
      display: flex;
      align-items: center;
      width: 100%;
      justify-content: center;
    }
    .name {
      color: #333;
      font-size: 14px;
      margin: 0 3px;
    }
    &.is-error {
      .name {
        color: #999999
      }
    }
    &:hover {
      .delete-icon {
        display: block;
      }
    }
  }

}
.upload-tip {
  cursor: pointer;
  color: #406eff;
  margin-top: 8px;
  font-size: 14px;
  text-decoration: underline;
}
.product-flex {
  display: flex;
  align-items: center;
}
</style>
